﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
using MegaBitProject.Models;

namespace MegaBitProject.Controllers
{
    // Game hub for Tic tac toe

    public class GameHubTTT : Hub
    {
        IGameRepository rep = new GameRepository();

        // When som1 join the hub
        public void Join(string groupID, string userName)
        {
            Groups.Add(Context.ConnectionId, groupID);
            Clients.OthersInGroup(groupID).userJoin(userName);
        }

        // When some user click cell
        public void ClickCell(string groupID, string cellID)
        {
            // Tell the other one which cell he clicked 
            Clients.OthersInGroup(groupID).cellClicked(cellID);
        }

        // Function that receive guss from users and check if it's the right word
        public void addMessage(string groupID, string userName, string message)
        {
            Clients.OthersInGroup(groupID).newMessage(userName, message);
        }

        // Update users score by id
        public void UpdateScore(string id)
        {
            if (!(String.IsNullOrEmpty(id)))
            {
                rep.updateScore(id, 1);
            }
        }

        // Update users stats by id
        public void updateStats(string id, string result)
        {
            if (!(String.IsNullOrEmpty(id)))
            {
                Statistic s = new Statistic();

                s.result = result.ToLower();
                s.userID = (from user in rep.getUser
                            where user.UserName.ToLower() == id.ToLower()
                            select user).SingleOrDefault();

                rep.updateStats(s);
            }
        }
    }
}